CFLAGS = -nostdlib -fno-builtin -march=rv64ima -mabi=lp64 -g -Wall

QEMU = qemu-system-riscv64
QFLAGS = -nographic -smp 1 -machine virt -bios none

CC_LIST := riscv64-unknown-elf- riscv64-linux-gnu-
CROSS_COMPILE ?= $(shell for cc in $(CC_LIST); do which $${cc}gcc >/dev/null 2>&1 && echo $${cc} && break; done)

ifneq ($(CROSS_COMPILE),)
  GDB_LIST := $(CROSS_COMPILE)gdb gdb-multiarch
  GDB ?= $(shell for gdb in $(GDB_LIST); do which $${gdb} >/dev/null 2>&1 && echo $${gdb} && break; done)

  GCC = ${CROSS_COMPILE}gcc
endif

ifeq ($(GCC),)
  $(error Please install one of $(addsuffix gcc,$(CC_LIST)))
else
  ifeq ($(GDB),)
    $(error Please install one of $(GDB_LIST))
  endif
endif

ifneq ($(shell which $(QEMU) >/dev/null 2>&1; echo $$?),0)
  $(error Please install $(QEMU))
endif

ifeq ($(CROSS_COMPILE),riscv64-linux-gnu-)
  # make sure PIE disabled for kernel-like binaries
  CFLAGS += -fno-PIE -mcmodel=medany

  # mem.S not work with riscv64-linux-gnu-, the addresses in mem.S can not be resolved, which breaks the whole mem management support
  # use mem.h instead of mem.S in such case
  CFLAGS += -DMEM_H
else
  # mem.S work well with riscv64-unknown-elf-
  CFLAGS += -DMEM_S
endif

CC = ${GCC}
OBJCOPY = ${CROSS_COMPILE}objcopy
OBJDUMP = ${CROSS_COMPILE}objdump
